package com.leemz.design.chapter4.pattern;

import com.leemz.design.chapter4.none.LogDbOperateApi;
import com.leemz.design.chapter4.none.LogFileOperateApi;
import com.leemz.design.chapter4.none.LogModel;

import java.util.List;

public class Adapter implements LogDbOperateApi {

    /**
     * 持有需要适配的接口对象，通过构造方法传入
     */
    private LogFileOperateApi adaptee;
    public Adapter(LogFileOperateApi adaptee) {
        this.adaptee = adaptee;
    }

    @Override
    public void createLog(LogModel logModel) {
        //实现之前的记录文件日志的功能
        List<LogModel> list = adaptee.readLogFile();
        list.add(logModel);
        adaptee.writeLogFile(list);
        //TODO 实现第二版中写入数据库日志的功能
    }

    @Override
    public void updateLog(LogModel logModel) {
        List<LogModel> list = adaptee.readLogFile();
        for (int i = 0; i < list.size(); i++) {
            if(list.get(i).getLogId().equals(logModel.getLogId())) {
                list.set(i, logModel);
                break;
            }
        }
        adaptee.writeLogFile(list);
    }

    @Override
    public void deleteLog(LogModel logModel) {
        List<LogModel> list = adaptee.readLogFile();
        list.remove(logModel);
        adaptee.writeLogFile(list);
    }

    @Override
    public List<LogModel> getAllLogs() {
        return adaptee.readLogFile();
    }
}
